package ynu.edu.api.client.fallback;

import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import ynu.edu.api.client.PermissionFeignClient;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class PermissionFeignClientFallbackFactory implements FallbackFactory<PermissionFeignClient> {

    @Override
    public PermissionFeignClient create(Throwable cause) {
        return new PermissionFeignClient() {

            @Override
            public List<String> getPermissions(Long userId) {
                if (cause instanceof RequestNotPermitted) {
                    log.error("RateLimiter限流触发，用户ID：{}", userId);
                } else {
                    log.error("其他异常，用户ID：{}，异常：{}", userId, cause.getMessage());
                }
                return new ArrayList<>();
            }

            @Override
            public List<String> getRoles(Long userId) {
                log.error("获取用户角色失败，用户ID：{}，异常信息：{}", userId, cause.getMessage());
                return new ArrayList<>();
            }

            @Override
            public void assignDefaultRole(Long userId) {
                log.error("分配默认角色失败，用户ID：{}，异常信息：{}", userId, cause.getMessage());
            }
        };
    }
}
